package com.example.rg.generator.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.rg.generator.DTO.SetmealDto;
import com.example.rg.generator.commons.CustomException;
import com.example.rg.generator.domain.Dish;
import com.example.rg.generator.domain.Setmeal;
import com.example.rg.generator.domain.SetmealDish;
import com.example.rg.generator.service.DishService;
import com.example.rg.generator.service.SetmealDishService;
import com.example.rg.generator.service.SetmealService;
import com.example.rg.generator.mapper.SetmealMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author DABB
 * @description 针对表【setmeal(套餐)】的数据库操作Service实现
 * @createDate 2023-04-28 09:43:31
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;


    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //查询套餐是否能删除
        LambdaQueryWrapper<Setmeal> lqwSetmeal = new LambdaQueryWrapper<>();
        lqwSetmeal.in(Setmeal::getId, ids);
        lqwSetmeal.eq(Setmeal::getStatus, 1);

        int count = this.count(lqwSetmeal);
        //弹出错误
        if (count > 0) {
            throw new CustomException("套餐在售，无法删除");
        }
        //删除表中数据
        this.removeByIds(ids);

        LambdaQueryWrapper<SetmealDish> lqwSetmealDish = new LambdaQueryWrapper<>();
        //根据套餐id删除口味数据
        lqwSetmealDish.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(lqwSetmealDish);

    }
}




